/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Stream.Base.js
 * @path:   js-src/Stream/
 * @desc:   Stream模块下基础业对象类
 * @author: jiegang@qiyi.com
 * @date:   2015-01-10
 */
qui(
    function (require, exports, module) {


        Stream.Grid = function (options) {
            this.dao = Stream.Dao;
            this.id = Ancestor.Util.getUrlId('id');
            this.qipuId = Ancestor.Util.getUrlId('qipuId');
            //    this.name = decodeURI(Ancestor.Util.getUrlId('name'));
            this.name = decodeURIComponent(Ancestor.Util.getUrlId('name'));
            this.config = Stream.Config;
            this.dlg = $("#stream-operate-dlg");
            this.videoTypeDlg = $("#video-type-operate-dlg");
            this.threeDDlg = $("#three-d-operate-dlg");
            this.streamsPreviewDlg = $("#streams-preview-dlg");
            this.options = options || {};
        };

        Com.inherits(Stream.Grid, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.bindEvent();
                self.initConfigOfType({
                    'sn': 'RtmpLocation',
                    'sk': 'DEST'
                }); // 地区
                self.initConfigOfType({
                    'sn': 'video_type',
                    'sk': 'VIDEO_TYPE'
                }); // 全景直播
                self.initCutterIdInfoNew("FLV");
                self.initCutterIdInfoNew("TS");
                $("#title").text(self.name);
            },

            initConfigOfType: function (options) {

                Ancestor.Dao.getType({
                    type: options.sn
                }, function (json) {
                    if (json.code == 'A00000') {
                        var config = Stream.Config[options.sk];
                        if (options.sn == 'RtmpLocation') {
                            config[''] = '';
                        }

                        $.each(json.data, function () {
                            if (options.sn == 'StreamType' || options.sn == 'RtmpLocation')
                                config[this.val] = this.descr;
                            else
                                config[this.key] = this.descr;
                        });

                    } else {
                        console.log('fail!');
                    }

                    if (typeof(options.requestLoaded) == 'function') {
                        options.requestLoaded();
                    }

                });

                //Channel.Dao.getSingleChannelData({'id':Ancestor.Util.getUrlId('id')},function(json) {
                //  if (json != 'undefined' && json.code == 'A00000') {
                //      // TODO delete after test
                //      json.data.pageUrl = 'http://www.iqiyi.com/c_19rron6ph6.html';
                //
                //      Stream.Config.CHANNEL_INFO = json.data;
                //  }
                //});

            },

            initCutterIdInfo: function (cutterType) {
                self.cutterType = cutterType;
                if (cutterType !== "FLV" && cutterType !== "TS") {
                    console.log("cutterType " + cutterType + " is not correct.");
                    return;
                }

                Stream.Dao.getCutterIdInfo({maxVal: 20, cutterType: cutterType}, function (json) {
                    if (json.code == 'A00000') {
                        var config = Stream.Config.CUTTER_ID[cutterType];

                        var cutterIdVal, descVal, countVal;

                        $.each(json.data, function () {
                            cutterIdVal = parseInt(this.cutterId);
                            descVal = this.desc;
                            countVal = this.count;

                            config.push({
                                cutterIdVal: cutterIdVal,
                                desc: descVal,
                                count: 20 - parseInt(countVal)
                            })
                        });
                    } else {
                        console.log('init CutterIdInfo failed!')
                    }
                })
            },

            initCutterIdInfoNew: function (cutterType) {
                self.cutterType = cutterType;
                if (cutterType !== "FLV" && cutterType !== "TS") {
                    console.log("cutterType " + cutterType + " is not correct.");
                    return;
                }

                var request = {};
                request.url = Stream.Config.CUTTERINFO_URL[cutterType];
                request.type = 'get';

                request.params = {};
                request = JSON.stringify(request);

                Stream.Dao.getCutterIdInfoNew({request: request}, function (json) {
                    if (json.status == '1') {
                        var config = Stream.Config.CUTTER_ID[cutterType];

                        var cutterIdVal, descVal, countVal;
                        var goodList = ['c12', 'c13', 'c15', 'c17', 'c18', 'c19', 'c20', 'c21', 'c22', 'c23', 'c24', 'c25', 'c26', 'c27', 'c28', 'c29'];

                        for (var key in json.data.remain) {
                            cutterIdVal = parseInt(key.slice(1));
                            descVal = key;
                            countVal = parseInt(json.data.remain[key]);

                            if (countVal !== 0) {
                                config.push({
                                    cutterIdVal: cutterIdVal,
                                    desc: descVal,
                                    count: countVal,
                                    good: $.inArray(descVal, goodList)
                                })
                            }
                        }
                        ;
                        config.sort(function (a, b) {
                            return b.count - a.count
                        });
                    } else {
                        console.log('init CutterIdInfo failed!')
                    }
                });

            },


            run: function () {
                var self = this;
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.initConfigOfType({
                            'sn': 'StreamType',
                            'sk': 'TYPE',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                }); // 流清晰度
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.initConfigOfType({
                            'sn': 'StreamStatus',
                            'sk': 'STATUS',
                            requestLoaded: ajaxBasicRequestLen
                        });
                    }
                });

                //
                self.ajaxBasicRequestQueue.pushData({
                    func: function (ajaxBasicRequestLen) {
                        self.dao.getChannelData({qipuId: self.qipuId}, function (data) {
                            if (data != null && data.code == 'A00000') {
                                self.config.CHANNEL_INFO = data.data.result[0];
                                console.log("Stream.Config.CHANNEL_INFO " + Stream.Config.CHANNEL_INFO.status);
                                Stream.Util.doVRSQuery(function () {
                                    ajaxBasicRequestLen();
                                })
                            } else {
                                console.log("vrs 接口访问失败");
                                ajaxBasicRequestLen();
                            }
                        })
                    }
                })

                self.ajaxBasicRequestManage.init(self, function (obj) {
                    obj.start();
                });
            },

            start: function (options, callback) {

                var self = this,
                    gridConfig = self.getGridConfig();

                self.init();

                self.echoQuery();
                options = $.extend(true, {
                    // width: 1500,
                    shrinkToFit: false
                    // autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
            },

            initGrid: function (options, callback) {
                var self = this;

                var gridConfig = self.getGridConfig();

                var $gridContainer = self.options.$container;

                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',

                    postData: {
                        fatherId: self.id
                    },
                    multiselect: true,
                    multiselectWidth: 30

                }, gridConfig, options);


                $grid.jqGrid('scroll', {});
                $grid.jqGrid(options);

                var params = $grid.jqGrid("getGridParam");
                params.rowNum = 500;
                params.pages = 1;

                if (Ancestor.Util.getUrlId('livetype') != Stream.Config.ENCODER_CONFIG.liveType_lb) {
                    $grid.hideCol("dest");
                }

            },

            query: function () {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                Stream.Config.TABLE.jsonReader = {

                    root: "data",

                    page: "pageNo",

                    total: "totalPages",

                    records: "totalCount"

                };

                $grid.jqGrid('setGridParam', {
                    postData: {
                        fatherId: self.id
                    }
                }).trigger('reloadGrid', [
                    {
                        page: 1
                    }
                ]);

            },

            getParam: function () {
                var self = this;
                var params = {};
                params.id = self.id;

                return params;

            },

            bindEvent: function () {
                var self = this;
                self.bindBasicEvent();
            },


            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;


                // 添加码流
                $container.find('.add-stream').click(function () {
                    self.addStreamShow({
                        title: '添加码流',
                        callback: "onAddStream"
                    });

                    var id = self.id,
                        name = self.name,
                        liveType = Ancestor.Util.getUrlId('livetype'),
                        universalCode = Ancestor.Util.getUrlId('universalcode'),
                        carouselDefaultStream = 'HIGH_DEFINITION',
                        playType = Stream.Config.CHANNEL_INFO.type == 6 ? 1 : 0;
                    $tmpl = $("#add-stream");

                    self.dlg.html($tmpl.tmpl({
                        channelName: name,
                        fatherId: id,
                        operate: 'add',
                        liveType: liveType,
                        universalCode: universalCode,
                        streamType: Stream.Config.TYPE,
                        cutterIdsFlv: Stream.Config.CUTTER_ID.FLV,
                        cutterIdsTs: Stream.Config.CUTTER_ID.TS,
                        cutterIdFlv: '0',
                        cutterIdTs: '0',
                        dest: Stream.Config.DEST,
                        carouselDefaultStream: carouselDefaultStream,
                        playType: playType,
                        backupEachOther: 1
                    }));
                    Stream.Util.streamNameSuggest($('input.streamNameSuggest'));
                    Stream.Util.dolbyStreamNameSuggest($('input.dolbyStreamNameSuggest'));
                    Stream.Util.encodeTypeSwitch($('#stream-operate-dlg'))
                });

                // 全景直播参数
                $container.find('.add-video-type').click(function () {

                    var id = self.id,
                        $tmpl = $("#add-video-type"),
                        videoTypeInfo = {
                            'videoType': 1,
                            'angleX': 0,
                            'angleY': 0,
                            'zoomRate': '1.0'
                        };

                    Channel.Dao.getSingleChannelData({
                        'id': self.id
                    }, function (json) {
                        if (json.code == 'A00000' && typeof(json.data.panoFormat) != 'undefined') {
                            videoTypeInfo = JSON.parse(json.data.panoFormat);
                            videoTypeInfo.zoomRate = videoTypeInfo.zoomRate.toFixed(1);
                        }

                        self.addVideoTypeShow({
                            title: '全景直播参数',
                            callback: "onAddVideoType"
                        });
                        self.videoTypeDlg.html($tmpl.tmpl({
                            fatherId: id,
                            videoType: Stream.Config.VIDEO_TYPE,
                            videoTypeValue: videoTypeInfo['videoType'],
                            angleX: videoTypeInfo['angleX'],
                            angleY: videoTypeInfo['angleY'],
                            zoomRate: videoTypeInfo['zoomRate']
                        }));
                    });
                });

                // 3D直播参数
                $container.find('.three-d').click(function () {

                    var id = self.id,
                        $tmpl = $("#three-d"),
                        videoTypeInfo = {
                            'videoType': 1
                        };

                    Channel.Dao.getSingleChannelData({
                        'id': self.id
                    }, function (json) {
                        if (json.code == 'A00000' && typeof(json.data.threeD) != 'undefined') {
                            videoTypeInfo = JSON.parse(json.data.threeD);
                        }

                        self.saveThreeDShow({
                            title: '3D直播参数',
                            callback: "onSaveThreeD"
                        });
                        self.threeDDlg.html($tmpl.tmpl({
                            fatherId: id,
                            videoType: Stream.Config.THREE_D_VIDEO_TYPE,
                            videoTypeValue: videoTypeInfo['videoType']
                        }));
                    });
                });


                // 编码流预览
                $container.find('.streams-preview').click(function () {


                    Stream.Dao.getStreamInfo({
                        'fatherId': self.id,
                        'formatType': 'flv'
                    }, function (json) {
                        if (json.code == 'A00000' && json.data.length > 0) {
                            var $grid = self.$grid;
                            var datas = $grid.jqGrid('getData');
                            var result = {};
                            $.each(datas, function (i, element) {
                                result[element.streamName] = element;
                            });

                            Stream.Config.STREAMS_INFO = result;

                            var videoDatas = {};

                            $.each(json.data, function (i, data) {
                                var sn = data.streamName;
                                videoDatas[sn] = {};
                                videoDatas[sn].flv = data.url;
                                videoDatas[sn].rtmp = 'rtmp://' + result[sn].internalIp + '/live/' + sn;
                                videoDatas[sn].rtmpIp = result[sn].streamIp;
                                videoDatas[sn].streamType = Stream.Config.TYPE[result[sn].streamType];
                                if (result[sn].hasOwnProperty('inputSignal') && result[sn].inputSignal != "") {
                                    videoDatas[sn].inputSignal = result[sn].inputSignal;
                                    if (videoDatas[sn].inputSignal.split(':')[0] === 'rtmp') {
                                        videoDatas[sn].inputSignalType = 'rtmp'
                                    } else {
                                        videoDatas[sn].inputSignalType = 'else'
                                    }
                                } else {
                                    videoDatas[sn].inputSignal = '没有信号源信息'
                                    videoDatas[sn].inputSignalType = 'empty'
                                }

                            });

                            self.parsePlayer.call(self, videoDatas);

                        } else if (json.code == 'A00000' && json.data.length == 0) {
                            $(document).tips({
                                content: "没有正在编码中的流，无法预览!",
                                type: "error"
                            });
                        } else {
                            var msg = "获取流信息错误!";
                            if (json.msg != undefined)
                                msg = json.msg;

                            $(document).tips({
                                content: msg,
                                type: "error"
                            });
                        }


                    });

                });

                $container.find('.switch-backup').click(function () {
                    //$('.switch-backup').prop("disabled", "disabled");
                    $(document).tips({
                        content: "切换灾备中",
                        type: "loading"
                    });
                    Stream.Dao.switchBackup({
                        'fatherId': self.id,
                        'qipuId': self.qipuId
                    }, function (json) {
                        if (typeof(json) != 'undefined') {
                            if (json.code == 'A00000') {
                                $(document).tips({content: json.msg, type: "success"});
                                // 刷新页面
                                setTimeout("location.reload()", 1000);
                            } else if (json.data == "-1") {
                                $(document).tips({content: "切流失败，必须同一清晰度只有两条且编码中，一条上线一条下线", type: "error"});
                            } else {
                                $(document).tips({content: "操作失败", type: "error"});
                            }
                        } else {
                            $(document).tips({content: "操作失败", type: "error"});
                        }

                        //$('.switch-backup').removeAttr("disabled");

                    })
                });
            },

            parsePlayer: function (videoDatas) {
                var self = this;
                var id = self.id,
                    $tmpl = $("#streams-preview");

                var tvId = '0';
                var cId = '0';
                var pageUrl = Stream.Config.CHANNEL_INFO.pageUrl;
                var request = {};
                request.fatherId = self.id;

                request.startDate = Com.date.format(new Date(), "yyyy-MM-dd 00:00:00");
                request.endDate = Com.date.format(new Date(), "yyyy-MM-dd hh:mm:ss");

                Stream.Dao.getCurrentProgram(request, function (json) {
                    if (json.code == 'A00000' && json.data.result.length > 0) {
                        var result = json.data.result;
                        var program = result[result.length - 1];
                        //pageUrl = program.pageUrl.split('?')[0];
                        tvId = program.qipuId;
                        cId = Stream.Config.CHANNEL_INFO.qipuId;

                    }

                    self.addStreamsPreviewShow({
                        title: '编码流预览'
                    });
                    self.streamsPreviewDlg.html($tmpl.tmpl({
                        vDatas: videoDatas,
                        tvId: tvId,
                        channelId: cId,
                        pageUrl: pageUrl
                    }));
                });


            },

            flvPlayer: function (src) {
                return '<embed width="100%" height="300"' +
                    ' src="http://www.iqiyi.com/common/flashplayer/20141218/LivePlayer_3_0_3_4.swf" ' +
                    'quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
                    ' align="middle"' +
                    ' play="true"' +
                    ' loop="true"' +
                    ' scale="showall"' +
                    ' wmode="window"' +
                    ' devicefont="false"' +
                    ' bgcolor="#000000"' +
                    ' name="player"' +
                    ' menu="true"' +
                    ' allowfullscreen="true"' +
                    ' allowscriptaccess="always"' +
                    ' flashvars="vid=' + src + '&source=live.lego.iqiyi.com&cid=qc_100001_300089"' +
                    ' salign="" ' +
                    'type="application/x-shockwave-flash">';
            },

            rtmpPlayer: function (src) {
                return '<embed src="swfs/StrobeMediaPlayback.swf" width="100%" height="300" id="StrobeMediaPlayback" quality="high" bgcolor="#000000"' +
                    'name="StrobeMediaPlayback" allowfullscreen="true" pluginspage="http://www.adobe.com/go/getflashplayer"' +
                    'flashvars="src=' + src + '&autoHideControlBar=true&streamType=live&autoPlay=false&verbose=true" type="application/x-shockwave-flash">';
            },

            // 添加流
            addStreamShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#stream-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 600,
                    //height:320,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });

            },

            // 添加全景直播参数
            addVideoTypeShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#video-type-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 400,
                    height: 280,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                $(document).tips({
                                    content: "页面提交中",
                                    type: "loading"
                                });

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },


            // 添加3D直播参数
            saveThreeDShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#three-d-operate-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 400,
                    height: 280,
                    //maxHeight: 320,
                    position: ['center', 'top+20'],
                    buttons: [
                        {
                            text: '确定',
                            click: function () {

                                $(document).tips({
                                    content: "页面提交中",
                                    type: "loading"
                                });

                                self[obj.callback](this);
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },

            // 添加编码流预览
            addStreamsPreviewShow: function (obj) {

                var self = this;
                var _options = self.options;
                var $container = $('#streams-preview-dlg');
                $container.dialog({
                    title: obj.title,
                    appendTo: null,
                    modal: true,
                    width: 1200,
                    height: 900,
                    //maxHeight: 320,
                    position: ['center', 'center'],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                    },
                    close: function () {
                    }
                });
            },


            // 填加
            onAddStream: function (obj) {

                $(document).tips({
                    content: "页面提交中",
                    type: "loading"
                });

                var self = this;

                var $form = $(".stream-add-form"),
                    params = {};
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    key,
                    peerCount = null;

                var encodeType = $form.find("select[name=encodeType]").val();

                $.each($elements, function () {
                    name = this.name;
                    if (Ancestor.Util.getUrlId('livetype') == '3' && name == 'streamName' && $(this).val().split('_')[0] != 'lb') {
                        $(document).tips({
                            content: '流名称只能以"lb_"开头',
                            type: "error"
                        });

                        peerCount = 1;
                    }
                    if (name == 'peerCount' && $(this).val() > 157) {
                        $(document).tips({
                            content: '镜像服务器数不能大于157',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamIp' && $(this).val() == '' && encodeType == 0) {
                        $(document).tips({
                            content: '请填写RTMP IP',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamAddress' && $(this).val() == '' && encodeType == 1) {
                        $(document).tips({
                            content: '请填写流地址',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'streamIp' && $(this).val().split('.')[0] == 10) {
                        $(document).tips({
                            content: 'RTMP ip非外网ip,请填写外网ip',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'dest' && $(this).val() == '') {
                        $(document).tips({
                            content: '请选择一个地区',
                            type: "error"
                        });

                        peerCount = 1;
                    }

                    if (name == 'bcsNum') {
                        var bcsVal = $(this).val();
                        if (bcsVal > 10 || bcsVal < 3 || isNaN(bcsVal) || parseInt(bcsVal) + '' !== bcsVal) {
                            $(document).tips({
                                content: '广播源数填写错误',
                                type: "error"
                            });

                            peerCount = 1;
                        }
                    }

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $(this).val() || '';
                });

                if (peerCount)
                    return;

                Stream.Dao.addStreamData(params, function (json) {
                    if (json.code == 'A00000' || 'EPG00202' || 'EPG00203') {

                        self.query();

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            onSaveThreeD: function (obj) {
                var self = this;

                var $form = $(".three-d-form"),
                    params = {
                        channelId: self.id
                    };

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    count = null;
                $.each($elements, function () {
                    name = this.name;

                    params[name] = params[name] = $(this).val() || '';
                });

                if (count) return;

                Stream.Dao.saveThreeD(params, function (json) {
                    if (json.code == 'A00000') {

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });
            },

            onAddVideoType: function (obj) {

                var self = this;

                var $form = $(".video-type-add-form"),
                    params = {
                        channelId: self.id
                    };
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    count = null;
                $.each($elements, function () {
                    name = this.name;
                    if (name == 'angleX' && $(this).val() < 0) {
                        $(document).tips({
                            content: '默认视角X轴不能小于0',
                            type: "error"
                        });

                        count = 1;
                    }
                    if (name == 'angleY' && $(this).val() < 0) {
                        $(document).tips({
                            content: '默认视角Y轴不能小于0',
                            type: "error"
                        });
                        count = 1;
                    }
                    if (name == 'zoomRate' && $(this).val() <= 0) {
                        $(document).tips({
                            content: '默认缩放系数必须大于0',
                            type: "error"
                        });
                        count = 1;
                    }

                    params[name] = params[name] = $(this).val() || '';
                });

                if (count) return;

                Stream.Dao.addVideoTypeData(params, function (json) {
                    if (json.code == 'A00000') {

                        var html = json.msg; //'添加成功';
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                    } else {
                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            // 修改直播流前检查
            onModifyStreamCheck: function (data) {
                var beforeData = Stream.Config.BEFORE_DATA;
                var msg = "如需立即生效，请将该直播流的FLV和TS停止，删除，重新创建。";
                if (!beforeData || !beforeData.hasOwnProperty('bcsNum') || !beforeData.hasOwnProperty('cutterIdTs') || !beforeData.hasOwnProperty('cutterIdFlv') || !beforeData.hasOwnProperty('peerCount')) {
                    $(document).tips({
                        content: '发生异常，请重新修改',
                        type: "error"
                    });
                } else {
                    if (beforeData.bcsNum + '' !== data.bcsNum || beforeData.cutterIdFlv + '' !== data.cutterIdFlv ||
                        beforeData.cutterIdTs + '' !== data.cutterIdTs || beforeData.peerCount + '' !== data.peerCount) {

                        SystemDialog.queryAlert(msg);
                    }
                    return true;
                }

                return false;
            },

            // 修改直播流
            onModifyStream: function (obj) {


                var $form = $(".stream-add-form"),
                    params = {};

                // 提交前验证
                var validator = Channel.Util.getValidator($form, Stream.Config.STREAM_FORM);
                if (!validator.form())
                    return;


                $(document).tips({
                    content: "页面提交中",
                    type: "loading"
                });

                var self = this;


                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name,
                    key,
                    peerCount;

                $.each($elements, function () {
                    name = this.name;
                    if (name == 'peerCount' && $(this).val() > 157) {
                        $(document).tips({
                            content: '镜像服务器数不能大于157',
                            type: "error"
                        });

                        peerCount = 1;
                    }


                    if (name == 'bcsNum') {
                        var bcsVal = $(this).val();
                        if (bcsVal > 10 || bcsVal < 3 || isNaN(bcsVal) || parseInt(bcsVal) + '' !== bcsVal) {
                            $(document).tips({
                                content: '广播源数填写错误',
                                type: "error"
                            });

                            peerCount = 1;
                        }
                    }

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $(this).val() || '';
                });

                if (peerCount)
                    return;


                //if(!self.onModifyStreamCheck(params)){
                //    return;
                //}

                Stream.Dao.modifyStreamData(params, function (json) {
                    if (json.code == 'A00000' || 'EPG00204') {

                        self.query();

                        var html = '';
                        if (json.code == 'A00000') {
                            html = '修改成功';
                        } else {
                            html = json.msg;
                        }
                        $(document).tips({
                            content: html,
                            type: "success"
                        });
                        $(obj).dialog('close');

                        self.onModifyStreamCheck(params)

                    } else {

                        var msg = Stream.Config.REQUEST_FAIL;
                        if (json.msg != undefined)
                            msg = json.msg;

                        $(document).tips({
                            content: msg,
                            type: "error"
                        });


                    }

                });

            },

            // 删除
            onDelStream: function (obj) {
                var self = this;
                auth.getAuthData({
                    tips: 1,
                    url: '/epg/live_stream_delete.html'
                }, function (rt) {

                    if (rt) {
                        $(document).tips({
                            content: '很抱歉，您没有删除的权限!',
                            type: "error"
                        });

                        return;
                    }

                    //if(!window.confirm('你确定要删除吗？'))
                    //return;


                    SystemDialog.queryConfirm("你确定要删除吗？", function (flag) {
                        if (flag === true) {

                            $(document).tips({
                                content: "页面提交中",
                                type: "loading"
                            });

                            Stream.Dao.delStreamData(obj, function (json) {
                                if (json.code == 'A00000') {

                                    self.query();

                                    var html = '删除成功';
                                    $(document).tips({
                                        content: html,
                                        type: "success"
                                    });

                                } else {
                                    var msg = Stream.Config.REQUEST_FAIL;
                                    if (json.msg != undefined)
                                        msg = json.msg;

                                    $(document).tips({
                                        content: msg,
                                        type: "error"
                                    });


                                }

                            });
                        }
                    });
                });
            },


            playStream: function () {

                var self = this;
                var _options = self.options;
                var $container = _options.$container;
                $container.dialog({
                    title: '预览',
                    appendTo: _options.$form,
                    modal: true,
                    width: 800,
                    height: 600,
                    maxHeight: 600,
                    buttons: [
                        {
                            text: '确定',
                            click: function () {
                                self.onSelect();
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

                    },
                    close: function () {
                        self.onClose();
                    }
                });


            },


            streamInfo: function () {

                var self = this;
                var _options = self.options;
                var $container = _options.$container;
                $container.dialog({
                    title: '添加码流',
                    appendTo: _options.$form,
                    modal: true,
                    width: 800,
                    height: 600,
                    maxHeight: 600,
                    buttons: [
                        {
                            text: '确定',
                            click: function () {
                                self.onSelect();
                            }
                        }
                    ],
                    open: function () {
                        $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');


                    },
                    close: function () {
                        self.onClose();
                    }
                });


            },

            bindFormEvent: function ($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function (selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "minDate", selectedDate);
                    }

                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function (selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "maxDate", selectedDate);
                    }
                });
            }

        });

    }
);